package com.enjoy.basic.serializable;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by HP on 2019/7/15.
 */
public class MsgPackClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final int sendNumber;
    public MsgPackClientHandler(int sendNumber){
        this.sendNumber=sendNumber;
    }
    private AtomicInteger counter=new AtomicInteger(0);
    @Override//读取数据后的处理
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("client Accept:"+byteBuf.toString(CharsetUtil.UTF_8)+"and counter i:s"+ counter.incrementAndGet());
    }

    @Override//连接上以后做的事情
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
       User[] users=makeUsers();
        for (User user:users){
            System.out.println("send user:"+user);
            ctx.write(user);
        }
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /*生成用户实体类的数组，以供发送*/
    private User[] makeUsers(){
        User[] users=new User[sendNumber];
        User user =null;
        for(int i=0;i<sendNumber;i++){
            user=new User();
            user.setAge(i);
            String userName = "ABCDEFG --->"+i;
            user.setUserName(userName);
            user.setId("No:"+(sendNumber-i));
            user.setUserContact(
                    new UserContact(userName+"@xiangxue.com","133"));
            users[i]=user;
        }
        return users;
    }
}
